<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="referrer" content="never">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
  <script src="https://res.wx.qq.com/open/js/jweixin-1.1.0.js"></script>
  <title>文章详情</title>
  <style>
      * {
          margin: 0;
          padding: 0;
      }

      body {
          overflow-x: hidden;
          font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
          line-height: 1.6;
          color: #333;
          max-width: 100%;
          margin: 0;
          padding: 16px;
          box-sizing: border-box;
      }

      h1 {
          font-size: 24px;
          margin-bottom: 8px;
      }

      .meta {
          font-size: 14px;
          color: #666;
          margin-bottom: 16px;
      }

      #content {
          font-size: 16px;
          max-width: 100%;
          overflow-x: hidden;
      }

      #content img {
          max-width: 100%;
          height: auto;
          max-width: 100%;
      }

      .error {
          color: red;
          font-weight: bold;
      }

      #map-container {
          width: 100%;
          height: 400px;
      }

      .map-info {
          background-color: rgb(243, 243, 243);
      }
  </style>
</head>

<body>
<h2 id="title"></h2>
<div class="meta">
  <span id="organizer"></span>
</div>
<div id="content"></div>
<div class="meta" style="margin-top: 24px">
  <span id="readingText"></span>：<span id="readingVolume"></span>
</div>
<div class="map-info" onclick="handleToNavigation(this)"
     style="padding: 12px;border-radius: 6px 6px 0 0;display: none;align-items: center;justify-content: space-between;"
>
  <div>
    <div class="map-title" style="font-weight: bold;color: rgb(0,0,0)"></div>
    <div class="map-address" style="font-size: 14px;color: rgb(102,102,102)"></div>
  </div>
  <div class="navigation">
    <svg t="1737811730235" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
         p-id="4323" width="18" height="18"
    >
      <path d="M325.048 93.511l-60.030 59.435 357.181 359.631-360.184 356.603 59.522 59.93 420.207-416.043z"
            fill="#848484" p-id="4324"
      ></path>
    </svg>
  </div>
</div>

<script>
  let latitude, longitude, address
  let articleDetails = null

	/**
	 * 获取URL参数
	 * @param name
	 * @return {string|string}
	 */
  function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]')
    let regex = new RegExp('[\\?&]' + name + '=([^&#]*)')
    let results = regex.exec(decodeURIComponent(location.search))
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '))
  }

	/**
	 * 发起请求
	 * @param method
	 * @param url
	 * @param data
	 * @param callback
	 * @param contentType
	 */
  function makeRequest(method, url, data, callback, contentType) {
    let xhr = new XMLHttpRequest()
    xhr.open(method, url, true)
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          if (method === 'GET' && url.includes('getArticle')) {
            // For the second API, return the raw response text
            callback(null, xhr.responseText)
          } else {
            // For other APIs, parse as JSON
            try {
              if (xhr.responseText) {
                callback(null, JSON.parse(xhr.responseText))
              } else {
                callback(null, null)
              }
            } catch (error) {
              callback(new Error('Failed to parse response as JSON'), null)
            }
          }
        } else {
          callback(new Error('Request failed. Status: ' + xhr.status), null)
        }
      }
    }
    if (method === 'POST') {
      xhr.setRequestHeader('Content-Type', contentType || 'application/x-www-form-urlencoded')
      xhr.send(data)
    } else {
      xhr.send()
    }
  }

	/**
	 * 请求文章详情
	 * @return {Promise<void>}
	 */
  async function loadArticle() {
    let id = getUrlParameter('id')
    // 获取当前域名
    let domain = window.location.hostname

    makeRequest('GET', 'https://web.jiubeimao.com/cat/api/writings/getArticleDetails?id=' + id + '&domainUrl=' + domain, null, function(error, result) {
      if (error) {
        document.body.innerHTML = '<p class="error">加载文章详情失败: ' + error.message + '</p>'
        return
      }
      articleDetails = JSON.parse(result)
      if (articleDetails.data.displayReading == 1) {
        document.getElementById('readingVolume').textContent = articleDetails.data.quantity
        document.getElementById('readingText').textContent = '阅读量'
      } else if (articleDetails.data.displayPeople == 1) {
        document.getElementById('readingVolume').textContent = articleDetails.data.forwardNum
        document.getElementById('readingText').textContent = '转发量'
      }
      document.title = articleDetails.data.articleTitle
      address = articleDetails.data.activityAddress
      getWxConfig()
      let time = articleDetails.data?.advertTime || 10
      time = time * 1000
      // 延迟打开广告
      setTimeout(function() {
        openAd()
      }, time)
    })
    // makeRequest('GET', 'https://web.jiubeimao.com/cat/api/writings/getArticle/' + id, null, async function (error, articleContent) {
    //   if (error) {
    //     document.body.innerHTML = '<p class="error">加载文章内容失败: ' + error.message + '</p>'
    //     return
    //   }
    //
    //   // Create a temporary element to parse the HTML content
    //   let tempDiv = document.createElement('div')
    //   tempDiv.innerHTML = articleContent
    //
    //   // Remove any script tags for security
    //   let scripts = tempDiv.getElementsByTagName('script')
    //   for (let i = scripts.length - 1; i >= 0; i--) {
    //     scripts[i].parentNode.removeChild(scripts[i])
    //   }
    // })

    // Adjust image sizes
    let tempDiv = document.getElementById('content')
    let images = tempDiv.getElementsByTagName('img')
    for (let i = 0; i < images.length; i++) {
      let lat = images[i].getAttribute('data-lat')
      let lng = images[i].getAttribute('data-lng')
      if (lat && lng) {
        let address = images[i].getAttribute('data-address')
        let title = images[i].getAttribute('data-title')
        images[i].style.maxWidth = '100%'
        images[i].style.height = 'auto'

        // 复制map-info元素样式，插入到img标签之前
        let mapInfo = document.querySelector('.map-info')
        let mapInfoClone = mapInfo.cloneNode(true)
        mapInfoClone.style.display = 'flex'
        // 设置map-info元素中的map-title元素内容
        let mapTitle = mapInfoClone.querySelector('.map-title')
        mapTitle.innerText = title
        // 设置map-info元素中的map-address元素内容
        let mapAddress = mapInfoClone.querySelector('.map-address')
        mapAddress.innerText = address
        // 将map-info元素插入到img标签之前
        images[i].parentNode.insertBefore(mapInfoClone, images[i])
        mapInfoClone.setAttribute('lat', lat)
        mapInfoClone.setAttribute('lng', lng)
        mapInfoClone.setAttribute('address', address)
        mapInfoClone.setAttribute('title', title)
      }
    }

    // Record reading
    let postData = JSON.stringify({ id: id })
    makeRequest('POST', 'https://web.jiubeimao.com/cat/api/writings/inputArticleReadNum', postData, function(error) {
      if (error) {
        console.error('记录阅读次数失败:', error)
      }
    }, 'application/json')
  }

	/**
	 * 生成随机字符串
	 * @param length
	 * @return {string}
	 */
  function generateRandomString(length = 30) {
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    let result = ''
    const charactersLength = characters.length
    for (let i = 0; i < length; i++) {
      result += characters.charAt(Math.floor(Math.random() * charactersLength))
    }
    return result
  }

	/**
	 * 获取设备IP地址
	 * @return {Promise<unknown>}
	 */
  function getDeviceIp() {
    return new Promise((resolve, reject) => {
      makeRequest('GET', 'https://web.jiubeimao.com/cat/api/writings/getIpCode', null, function(error, result) {
        if (result.code === 200 && result.data && result.data.ipAddress) {
          resolve(result.data.ipAddress)
        } else {
          resolve('127.0.0.1')
        }
      })
    })
  }

	/**
	 * 请求广告
	 * @return {Promise<void>}
	 */
  async function requestAd() {
    const adSlotId = '472211' // 广告位ID

    // 构建广告请求体
    const requestBody = {
      id: generateRandomString(), // 随机生成的唯一ID
      imp: [
        {
          id: '1', // 曝光ID
          type: 1, // 广告类型：1 表示纯图广告
          pid: adSlotId, // 广告位ID
          banner: {
            h: 356, // 广告位高度
            w: 272, // 广告位宽度
            mimes: ['jpg', 'jpeg', 'png', 'gif'] // 支持的素材格式
          },
          bidfloor: 0 // 底价，单位：分/CPM
        }
      ],
      device: {
        ip: await getDeviceIp(), // 设备IP地址
        ua: navigator.userAgent // 设备User-Agent
      },
      secure: 1 // 返回链接必须为HTTPS
    }

    // 发送广告请求
    makeRequest('POST', 'https://adx.tuia.cn/bid/tuia', JSON.stringify(requestBody), function(error, result) {
      if (error) {
        console.error('广告请求失败:', error)
        return
      }

      const { seatbid = [] } = result

      // 提取广告素材、曝光回调和点击回调地址
      let adm, nurl, curl, durl
      seatbid.forEach((item) => {
        const bid = item.bid[0] || {}
        adm = bid.adm // 广告素材
        nurl = bid.nurl && bid.nurl[0] // 曝光回调地址
        curl = bid.curl && bid.curl[0] // 点击回调地址
        durl = bid.durl
      })

      if (adm && nurl && curl) {
        console.log('广告素材:', adm)
        console.log('曝光回调地址:', nurl)
        console.log('点击回调地址:', curl)

        // 广告展示时调用曝光回调
        makeRequest('GET', nurl, null, () => {
        })

        // 用户点击广告时调用点击回调
        const handleAdClick = () => {
          makeRequest('GET', curl, null, () => {
          })
          if (durl) window.open(durl)
        }
        // 渲染广告素材
        const adContainer = document.createElement('div')
        adContainer.style.position = 'relative'
        adContainer.style.left = '50%'
        adContainer.style.top = '50%'
        adContainer.style.transform = 'translate(-50%, -50%)'
        adContainer.style.textAlign = 'center'
        adContainer.innerHTML = `<img src="${JSON.parse(adm).imgurl}" alt="广告素材" style="max-width: 100%; height: auto;" />`
        adContainer.addEventListener('click', handleAdClick)

        // 创建遮罩层
        const overlay = document.createElement('div')
        overlay.style.position = 'fixed'
        overlay.style.top = '0'
        overlay.style.left = '0'
        overlay.style.width = '100%'
        overlay.style.height = '100%'
        overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.5)' // 半透明黑色
        overlay.style.zIndex = '9999' // 确保遮罩层在最上层
        overlay.style.overflow = 'hidden' // 限制滚动

        // 创建关闭按钮
        const closeButton = document.createElement('div')
        closeButton.innerHTML = '<svg t="1739187499040" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4343" width="32" height="32"><path d="M512 1024C229.376 1024 0 794.624 0 512S229.376 0 512 0s512 229.376 512 512-229.376 512-512 512z m0-975.36C257.024 48.64 48.64 257.024 48.64 512c0 254.976 207.872 463.36 463.36 463.36S975.36 767.488 975.36 512 766.976 48.64 512 48.64z" fill="#e6e6e6" p-id="4344"></path><path d="M548.864 512l195.072-195.072c9.728-9.728 9.728-25.6 0-36.864l-1.536-1.536c-9.728-9.728-25.6-9.728-35.328 0L512 475.136 316.928 280.064c-9.728-9.728-25.6-9.728-35.328 0l-1.536 1.536c-9.728 9.728-9.728 25.6 0 36.864L475.136 512 280.064 707.072c-9.728 9.728-9.728 25.6 0 36.864l1.536 1.536c9.728 9.728 25.6 9.728 35.328 0L512 548.864l195.072 195.072c9.728 9.728 25.6 9.728 35.328 0l1.536-1.536c9.728-9.728 9.728-25.6 0-36.864L548.864 512z" fill="#e6e6e6" p-id="4345"></path></svg>'
        closeButton.style.position = 'absolute'
        closeButton.style.top = '-30px'
        closeButton.style.right = '30px'
        closeButton.style.cursor = 'pointer'
        closeButton.addEventListener('click', (event) => {
          // 组织事件冒泡
          document.body.removeChild(overlay) // 移除遮罩层
          event.stopPropagation()
        })
        // 将关闭按钮添加到广告容器
        adContainer.appendChild(closeButton)
        // 将广告图片和关闭按钮添加到遮罩层
        overlay.appendChild(adContainer)

        // 将遮罩层添加到页面
        document.body.appendChild(overlay)
      } else {
        console.error('未获取到广告素材或回调地址')
      }
    }, 'application/json')
  }

	/**
	 * 处理地图导航
	 * @param event
	 */
  function handleToNavigation(event) {
    // 获取当前元素的经纬度信息
    let latitude = event.getAttribute('lat')
    let longitude = event.getAttribute('lng')
    let title = event.getAttribute('title')
    let address = event.getAttribute('address')
    if (!latitude || !longitude) {
      alert('未获取到坐标信息')
      return
    }
    let isWechat = /MicroMessenger/i.test(navigator.userAgent)
    if (isWechat) {
      wx.openLocation({
        latitude: Number(latitude), // 纬度，浮点数，范围为90 ~ -90
        longitude: Number(longitude), // 经度，浮点数，范围为180 ~ -180
        name: title, // 位置名
        address: address, // 地址详情说明
        scale: 15 // 地图缩放级别,整形值,范围从1~28。默认为最大
      })
    } else {
      alert('请在微信浏览器内打开')
    }
  }

	/**
	 * 微信配置
	 */
  function getWxConfig() {
    let articleData = articleDetails.data
    let id = getUrlParameter('id')
    let link = window.location.href // .split('?')[0] + '?id='+id
    makeRequest('POST', 'https://web.jiubeimao.com/cat/api/writings/getAppId', JSON.stringify({
      id,
      url: link
    }), function(error, result) {
      let data = result.data
      // 配置微信SDK
      wx.config({
        debug: false, // 开启调试模式，可以在微信开发者工具中查看日志
        appId: data.appId, // 必填，公众号的唯一标识
        timestamp: data.timeStamp, // 必填，生成签名的时间戳
        nonceStr: data.nonceStr, // 必填，生成签名的随机串
        signature: data.sign,// 必填，签名
        jsApiList: ['openLocation', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'hideMenuItems', 'showMenuItems']
      })
      wx.ready(function() {
        let link = window.location.href.split('?')[0] + '?id='+id
        wx.onMenuShareTimeline({
          title: articleData.articleTitle, // 分享标题
          link: decodeURIComponent(link), // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          imgUrl: articleData.wximg, // 分享图标
          trigger: function(res) {
            share()
          },
          success: function() {
            wx.showMenuItems({
              menuList: ['menuItem:share:timeline'] // 要显示的菜单项，所有menu项见附录3
            })
          }
        })
        wx.onMenuShareAppMessage({
          title: articleData.articleTitle, // 分享标题
          desc: articleData.wxsummary, // 分享描述
          link: decodeURIComponent(link), // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          imgUrl: articleData.wximg, // 分享图标
          trigger: function(res) {
            share()
          },
          success: function() {
            wx.showMenuItems({
              menuList: ['menuItem:share:appMessage'] // 要显示的菜单项，所有menu项见附录3
            })
          }
        })
      })
      wx.error(function(res) {
        console.error('微信SDK配置错误:', res)
      })
    }, 'application/json')
  }

	// 标志位，确保广告只触发一次
  let isAdTriggered = false
	/**
	 * 广告触发方法
	 */
	function openAd() {
    if (isAdTriggered) return // 如果广告已经触发过，直接返回
    isAdTriggered = true // 设置标志位为 true
    console.log('触发广告')
    // 请求广告
    requestAd()
  }

	/**
	 * 图片懒加载
	 */
  function initLazyLoading() {
    const imageObserver = new IntersectionObserver((entries, observer) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          const img = entry.target
          img.src = img.dataset.src
          img.removeAttribute('data-src')
          observer.unobserve(img)
        }
      })
    }, {
      rootMargin: '50px 0px' // 提前50px开始加载
    })

    // 获取所有需要懒加载的图片
    const lazyImages = document.querySelectorAll('img[data-src]')
    lazyImages.forEach(img => imageObserver.observe(img))
  }

  // 修改图片处理部分
  function processImages() {
    const images = document.getElementsByTagName('img')
    for (let i = 0; i < images.length; i++) {
      const img = images[i]

      // 设置图片加载时的占位样式
      img.style.opacity = '0'
      img.style.transition = 'opacity 0.3s ease-in'

      // 图片加载完成后显示
      img.onload = function() {
        this.style.opacity = '1'
      }

      // 处理懒加载
      if (!img.hasAttribute('data-src')) {
        const originalSrc = img.src
        img.setAttribute('data-src', originalSrc)
        img.src = '' // 清空src，等待懒加载
      }
    }

    // 初始化懒加载
    initLazyLoading()
  }

	/**
	 * 初始化图片加载
	 */
  function initImageLoading() {
    // 确保 DOM 已经加载
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', processImages)
    } else {
      processImages()
    }

    // 添加页面可见性变化监听
    document.addEventListener('visibilitychange', () => {
      if (document.visibilityState === 'visible') {
        processImages()
      }
    })
  }

	/**
	 * 记录分享次数
	 */
  function share() {
    setTimeout(() => {
      let id = encodeURIComponent(getUrlParameter('id'))
      makeRequest('POST', 'https://web.jiubeimao.com/cat/api/writings/forwardShare', JSON.stringify({
        id
      }), () => {
      }, 'application/json')
    }, 2000)
  }

  let ua = navigator.userAgent.toLowerCase()
  let isWeixin = ua.indexOf('micromessenger') != -1
  let isAndroid = ua.indexOf('android') != -1
  let isIos = (ua.indexOf('iphone') != -1) || (ua.indexOf('ipad') != -1)
  if (!isWeixin) {
    document.head.innerHTML = '<title>抱歉，出错了</title><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0"><link rel="stylesheet" type="text/css" href="https://res.wx.qq.com/open/libs/weui/0.4.1/weui.css">'
    document.body.innerHTML = '<div class="weui_msg"><div class="weui_icon_area"><i class="weui_icon_info weui_icon_msg"></i></div><div class="weui_text_area"><h4 class="weui_msg_title">请在微信客户端打开链接</h4></div></div>'
  } else {
    window.onload = function() {
      loadArticle()
      initImageLoading()
    }
  }
  let code = getUrlParameter('code');
  if(!code){
    let url = window.location.href
    const pattern = /wenzhang\/([^\/]+)\/article/;
    let link = url.replace(pattern, `wenzhang/${generateRandomString(6)}/article`);
    link += `&code=${generateRandomString(6)}`
    window.location.href = link
  }
</script>
</body>

</html>
